package com.lbj.servlet.user;

import com.alibaba.fastjson.JSON;
import com.lbj.bean.Role;
import com.lbj.bean.User;
import com.lbj.service.role.RoleService;
import com.lbj.service.role.RoleServiceImpl;
import com.lbj.service.user.UserService;
import com.lbj.service.user.UserServiceImpl;
import com.lbj.util.Constant;
import com.lbj.util.PageBean;
import com.mysql.cj.util.StringUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UpdatePwdServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("savepwd".equals(method)) {
            checkNewPwd(req, resp);
        } else if ("oldpwd".equals(method)) {
            checkOldPwd(req, resp);
        } else if ("query".equals(method)) {
            checkQuery(req, resp);
        }
    }

    private void checkQuery(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("queryname");
        String queryUserRole = req.getParameter("queryUserRole");
        String currentPageNo = req.getParameter("currentPageNo");
        int userRole = 0;
        int currentPage = 1;
        int pageSize = 5;

        if (StringUtils.isNullOrEmpty(username)) {
            username = "";
        }

        if (!StringUtils.isNullOrEmpty(queryUserRole)) {
            userRole = Integer.parseInt(queryUserRole);
        }

        if (!StringUtils.isNullOrEmpty(currentPageNo)) {
            currentPage = Integer.parseInt(currentPageNo);
        }

        UserService userService = new UserServiceImpl();
        // 用户数量
        int userCount = userService.getUserCount(username, userRole);
        // 用户列表
        List<User> userList = userService.getUserList(username, userRole, currentPage, pageSize);
        RoleService roleService = new RoleServiceImpl();
        // 角色列表
        List<Role> roleList = roleService.getRoleList();

        System.out.println("========================查询用户职位========================");
        for (Role role : roleList) {
            System.out.println("用户职位：" + role.getRoleName());
        }
        System.out.println("========================用户姓名========================");
        for (User user : userList) {
            System.out.println("用户姓名：" + user.getUserName());
        }
        System.out.println("========================用户数量========================");
        System.out.println("用户数量：" + userCount);

        PageBean<User> page = new PageBean();
        page.setPageNo(currentPage);
        page.setPageSize(pageSize);
        page.setTotalCount(userCount);
        page.setPageList(userList);

        req.setAttribute("queryUserName", username);
        req.setAttribute("roleList", roleList);
        req.setAttribute("userRole", userRole);
        req.getRequestDispatcher("userlist.jsp").forward(req, resp);
    }

    private void checkOldPwd(HttpServletRequest req, HttpServletResponse resp) {
        String oldpassword = req.getParameter("oldpassword");
        Object o = req.getSession().getAttribute(Constant.USER_SESSION);
        Map<String, String> map = new HashMap<>();

        if (StringUtils.isNullOrEmpty(oldpassword)) {
            map.put("result", "error");
        } else if (o == null) {
            map.put("result", "sessionerror");
        } else if (!oldpassword.equals(((User) o).getUserPassword())) {
            map.put("result", "false");
        } else {
            map.put("result", "true");
        }

        try {
            // 因为ajax
            resp.setContentType("application/json");
            PrintWriter out = resp.getWriter();
            out.write(JSON.toJSONString(map));
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void checkNewPwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String newPwd = req.getParameter("userPassword");
        Object o = req.getSession().getAttribute(Constant.USER_SESSION);
        boolean flag;
        if (o != null && !StringUtils.isNullOrEmpty(newPwd)) {
            UserService service = new UserServiceImpl();
            flag = service.updatePwd(((User) o).getUserCode(), newPwd);
            if (flag) {
                // 密码修改成功
                req.setAttribute("message", "密码修改成功，请重新登录");
                req.getSession().removeAttribute(Constant.USER_SESSION);
            } else {
                req.setAttribute("message", "密码修改失败");
            }
        } else {
            // 用户未登录或者新密码为空
            req.setAttribute("message", "用户未登录或者新密码为空");
        }

        req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
